<template>
  <div class="container">
    <div class="app-container">
      <el-button type="primary" size="mini" class="add-btn" @click="operatePermission(0, 'add')">添加权限</el-button>
      <el-table :data="permissionList" row-key="id" default-expand-all>
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="code" label="标识" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <el-row type="flex" justify="center">
              <el-button v-if="row.type === 1" type="text" size="mini" @click="operatePermission(row.id, 'add')">添加</el-button>
              <el-button type="text" size="mini" @click="operatePermission(row.id, 'edit')">编辑</el-button>
              <el-popconfirm title="您确定要删除吗？" @onConfirm="operatePermission(row.id, 'del')">
                <el-button slot="reference" style="margin-left:10px" type="text" size="mini">删除</el-button>
              </el-popconfirm>
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <add-permission ref="addPermission" :show-dialog.sync="showDialog" :current-node-id="currentNodeId" @success="onSuccess" />
  </div>
</template>
<script>
import { permissionListService, permissionDeleteService } from '@/api/permission'
import { transListToTreeData } from '@/utils'
import AddPermission from './components/AddPermission.vue'
export default {
  name: 'Permission',
  components: {
    AddPermission
  },
  data() {
    return {
      permissionList: [],
      showDialog: false,
      currentNodeId: 0
    }
  },
  created() {
    this.getPermissionList()
  },
  methods: {
    async getPermissionList() {
      this.permissionList = transListToTreeData(await permissionListService(), 0)
    },
    onSuccess() {
      this.getPermissionList()
      this.showDialog = false
    },
    async operatePermission(id, command) {
      if (command === 'add') {
        this.currentNodeId = id
        this.showDialog = true
      } else if (command === 'edit') {
        this.currentNodeId = id
        this.showDialog = true
        this.$nextTick(() => {
          this.$refs.addPermission.getPermissionDetail()
        })
      } else if (command === 'del') {
        await permissionDeleteService(id)
        this.$message.success('删除成功')
        this.getPermissionList()
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.add-btn {
  margin: 20px;
}
</style>
